import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { IIds } from '../interface/ids.interface';

@Injectable()
export class BaseService {

  constructor(@InjectModel('Ids') private readonly IdsModule: Model<IIds>) {}

  // id 自增
  async getId(type: string): Promise<number> {
    const idList: string[] = ['account_id'];
    if (idList.includes(type)) {
      const idInfo = await this.IdsModule.findOne();
      if (idInfo === null) {
        const newIds = new this.IdsModule({
          account_id: 0,
        });
        await newIds.save();
        const newIdInfo = await this.IdsModule.findOne();
        return await this.saveIds(newIdInfo, type);
      } else {
        return await this.saveIds(idInfo, type);
      }
    }
  }

  async saveIds(idInfo, type): Promise<number> {
    idInfo[type] ++;
    await idInfo.save();
    return idInfo[type];
  }

}